<script setup>
import request from '@/utils/request.js'
import { ref, computed, onMounted } from 'vue';
import { useUserStore,usePartnerStore } from '@/stores/index.js'
import { ElContainer, ElAside, ElMain, ElMenu, ElMenuItem, ElCard, ElButton, ElTimeline, ElTimelineItem, ElMessage, ElImage ,ElMessageBox} from 'element-plus';

// 状态管理
const activeGroupKey = ref(''); // 当前选中的小组ID（绑定groupId）
const newMessage = ref('');
const userStore = useUserStore();
const partnerStore = usePartnerStore();
const groups = ref([]); // 小组列表
const groupDynamics = ref({}); // 小组动态：key=groupId，value=动态数组

// 默认图片
const DEFAULT_AVATAR = 'https://placehold.co/50x50/cccccc/ffffff?text=用户';
const DEFAULT_GROUP_ICON = 'https://picsum.photos/id/119/50/50';

// 当前选中的小组（修正字段匹配）
const currentGroup = computed(() => {
  const key = String(activeGroupKey.value);
  return groups.value.find(group => String(group.groupId) === key) || {
    groupName: '未知小组',
    groupLeaderNickname: '未知组长',
    memberCount: 0
  };
});

// 当前小组的动态列表
const currentDynamics = computed(() => {
  return groupDynamics.value[activeGroupKey.value] || [];
});

// 1. 切换小组时加载动态
const handleGroupSelect = (groupId) => {
  activeGroupKey.value = groupId;
  getGroupPosts(groupId); // 传入小组ID加载动态
};

// 2. 获取小组动态（适配接口返回格式）
const getGroupPosts = async (groupId) => {
  try {
    const res = await request.get('/getGroupPosts', {
      params: { groupId: groupId }
    });

    // 格式化动态数据：映射接口字段到前端需要的格式
    const formattedDynamics = res.data.posts.map(post => ({
      id: post.postId, // 动态ID
      content: post.postContent, // 接口postContent → 前端content
      time: post.publishTime, // 接口publishTime → 前端time
      publisherNickname: post.publisherNickname, // 发布者昵称
      publisherAvatar: post.publisherAvatar || DEFAULT_AVATAR, // 发布者头像
      isMe: post.publisherId === userStore.userId // 是否为当前用户发布
    }));

    // 存储格式化后的动态
    groupDynamics.value[groupId] = formattedDynamics;

    // 无动态提示（接口返回的是pagination.totalPosts）
  } catch (error) {
    console.error('获取小组动态失败:', error);
    ElMessage({ type: 'error', message: '动态加载失败' });
    groupDynamics.value[groupId] = [];
  }
};

// 3. 获取用户加入的小组列表
const getUserGroups = async () => {
  try {
    const res = await request.get('/getUserGroups', {
      params: { userId: userStore.userId }
    });

    // 直接使用接口返回的小组数据（假设包含groupId、groupName等字段）
    groups.value = res.data;

    // 初始化：加载第一个小组的动态
    if (groups.value.length > 0) {
      const firstGroupId = String(groups.value[0].groupId);
      activeGroupKey.value = firstGroupId;
      getGroupPosts(firstGroupId);
    }
  } catch (error) {
    console.error('获取小组列表失败:', error);
    groups.value = [];
    ElMessage({ type: 'error', message: '小组列表加载失败' });
  }
};

// 4. 发送消息
const sendMessage = async (groupId) => {
  const res = await request.post('/sendGroupPost', {
    userId: userStore.userId,
    groupId: groupId,
    content: newMessage.value
  });
  getGroupPosts(groupId)
  newMessage.value = ''
  console.log("发送消息功能待实现");
};

// 工具函数：格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

//撤回小组动态
const groupChatWithdraw=(id)=>{
   // 是否确认撤回
  ElMessageBox.confirm('确定要撤回这条消息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
      try{
      const res = await request.post('/groupChatWithdraw',{
      id:id
    })
    if(res.status=200){
        ElMessage({ type: 'success', message: '消息撤回成功' });
    }
     await getGroupPosts(activeGroupKey.value);
    }catch(error){
      const errMsg = error.response?.data?.message || '消息撤回失败，请重试';
      // 显示后端返回的真实提示（比如“消息发送超过2分钟，无法撤回”）
      ElMessage({ type: 'error', message: errMsg });
      // 优化控制台日志：明确是业务提示，不是代码异常
      console.log('撤回操作提示:', errMsg);
    }
  }).catch(() => {

  });
}
// 页面挂载时初始化
onMounted(() => {
  getUserGroups();
});

// 弹窗显隐状态
const createGroupDialogVisible = ref(false);

// 表单数据：小组名称 + 学习目标
const groupForm = ref({
  name: '',
  goal: ''
});

// 打开创建小组弹窗
const openCreateDialog = () => {
  createGroupDialogVisible.value = true;
};

// 提交“创建小组”请求
const handleCreateGroup = async () => {
  // 前置校验：小组名称不能为空
  if (!groupForm.value.name.trim()) {
    ElMessage.warning('小组名称不能为空');
    return;
  }

  try {
    // 调用后端“创建小组”接口（需与后端接口参数对齐）
    const res = await request.post('/createStudyGroup', {
      userId: userStore.userId,
      groupName: groupForm.value.name.trim(),
      description: groupForm.value.goal.trim()
    });
    // 成功提示 + 关闭弹窗
    ElMessage.success('小组创建成功');
    createGroupDialogVisible.value = false;
    getUserGroups();
  } catch (err) {
    // 失败提示
    ElMessage.error(err.response?.data?.message || '创建小组失败，请重试');
  }
};

const groupMembers = ref([]);
const inviteUserDialogVisible = ref(false);
const currentInviteId = ref(null);
const getGroupMembers = async () => {
  const res = await request.get('/getGroupMembers'
    , {
      params: {
        groupId: activeGroupKey.value,
      }
    }
  );
  //剔除partner中的res.data中的伙伴
  groupMembers.value = partnerStore.partners.filter(partner => !res.data.some(member => member.userId === partner.partnerId));
  //每项加一个id字段，值从0开始，每项加1
  groupMembers.value = groupMembers.value.map((group, index) => ({
      ...group, // 保留原有字段（name、leader等）
      id: index + 1 // id = 索引+1（确保从1开始）
    }));
  console.log(groupMembers.value);
};
const openInviteUserDialogVisible = () => {
  getGroupMembers();
  inviteUserDialogVisible.value = true;
};
const inviteUserToGroup=async (partnerId) =>{
  const res = await request.post('/inviteUserToGroup', {
    inviterUserId: userStore.userId,
    targetUserId: partnerId,
    groupId: activeGroupKey.value
  })
  if(res.status===200){
    ElMessage.success(res.message)
  }
  getUserGroups();
}
</script>

<template>
  <div class="app-container">
    <el-container class="main-container">
      <!-- 左侧小组列表 -->
      <el-aside width="320px" class="partner-aside">
        <div class="menu-header">
          <h3 class="menu-title">小组列表</h3>
          <el-button type="primary" size="small" @click="openCreateDialog">创建小组</el-button>
        </div>
        <el-dialog
          v-model="createGroupDialogVisible"
          title="新建小组"
          width="480px"
          :close-on-click-modal="false"
        >
          <el-form :model="groupForm" label-width="60px">
            <!-- 小组名称（必填） -->
            <el-form-item label="小组名称" required>
              <el-input
                v-model="groupForm.name"
                placeholder="请输入小组名称"
                maxlength="50"
              />
            </el-form-item>
            <!-- 学习目标（可选） -->
            <el-form-item label="学习目标">
              <el-input
                v-model="groupForm.goal"
                type="textarea"
                placeholder="请输入学习目标（可选）"
                maxlength="200"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="createGroupDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleCreateGroup">确定</el-button>
            </span>
          </template>
        </el-dialog>
        <el-menu
          :default-active="activeGroupKey"
          class="partner-menu"
          @select="handleGroupSelect"
        >
          <div v-if="groups.length === 0" class="empty">暂无小组</div>
          <el-menu-item
            v-for="group in groups"
            :key="group.groupId"
            :index="String(group.groupId)"
            class="partner-menu-item"
          >
            <div class="partner-info">
              <span class="partner-name">{{ group.groupName }}</span>
              <span class="partner-desc">组长：{{ group.groupLeaderNickname }} | {{ group.memberCount }}人</span>
            </div>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 右侧动态展示区 -->
      <el-main class="content-main">
        <!-- 小组头部信息 -->
        <el-card class="chat-header">
          <div class="chat-header-content">
            <img :src="DEFAULT_GROUP_ICON" class="chat-header-avatar" />
            <div class="chat-header-info">
              <h3 class="chat-header-name">{{ currentGroup.groupName }}</h3>
              <p class="chat-header-desc">组长：{{ currentGroup.groupLeaderNickname }} | {{ currentGroup.memberCount }}人</p>
            </div>
            <el-button class="chat-header-btn" v-if="currentGroup.groupLeaderId==userStore.userId" type="primary" size="small" @click="openInviteUserDialogVisible">邀请伙伴</el-button>
            <el-dialog
              v-model="inviteUserDialogVisible"
              title="邀请伙伴加入小组"
              width="400px"
              :close-on-click-modal="false"
            >
              <div class="partner-dialog-container">
                <!-- 加载状态 -->
                <div v-if="partnerStore.isLoading" class="dialog-loading">
                  <el-loading size="small" text="加载中..." />
                </div>

                <!-- 无伙伴数据 -->
                <div v-else-if="partnerStore.partners.length === 0" class="dialog-empty">
                  暂无伙伴，先去添加吧～
                </div>

                <!-- 无可用邀请的伙伴 -->
                <div v-else-if="groupMembers.length === 0" class="dialog-empty">
                  所有伙伴已在当前小组
                </div>

                <!-- 简化的伙伴列表：仅名字 + 邀请按钮 -->
                <div v-else class="partner-list">
                  <div class="partner-item" v-for="partner in groupMembers" :key="partner.id">
                    <!-- 仅显示名字 -->
                    <span class="partner-name">{{ partner.nickname }}</span>

                    <!-- 邀请按钮（带加载状态） -->
                    <el-button
                      type="primary"
                      size="small"
                      @click="inviteUserToGroup(partner.partnerId)"
                      :loading="currentInviteId === partner.id"
                      :disabled="currentInviteId === partner.id"
                    >
                      邀请
                    </el-button>
                  </div>
                </div>
              </div>

              <template #footer>
                <el-button @click="inviteUserDialogVisible = false">取消</el-button>
              </template>
            </el-dialog>

          </div>
        </el-card>

        <!-- 小组动态列表 -->
        <el-card class="chat-records-card">
          <div class="chat-records-container">
            <el-timeline>
              <el-timeline-item
                v-for="(dynamic, idx) in currentDynamics"
                :key="dynamic.id || idx"
                :timestamp="formatTime(dynamic.time)"
                placement="top"
              >
                <!-- 发布者信息 -->
                <div class="publisher-info">
                  <span class="publisher-nickname">
                    {{ dynamic.publisherNickname }}
                    <span v-if="dynamic.isMe" class="is-me-tag">（我）</span>
                  </span>
                </div>
                <!-- 动态内容 -->
                <div class="dynamic-content-mine" v-if="dynamic.isMe" @click="groupChatWithdraw(dynamic.id)">
                  {{ dynamic.content }}
                </div>
                <div class="dynamic-content" v-else>
                  {{ dynamic.content }}
                </div>
              </el-timeline-item>
            </el-timeline>

            <!-- 无动态提示 -->
            <div v-if="currentDynamics.length === 0" class="no-dynamics">
              暂无动态，快来发布第一条动态吧~
            </div>
          </div>
        </el-card>

        <!-- 消息输入区域（暂留） -->
        <el-card class="chat-input-card">
          <div class="chat-input-container">
            <el-input
              v-model="newMessage"
              @keyup.enter="sendMessage(currentGroup.groupId)"
              type="textarea"
              :rows="3"
              placeholder="输入消息..."
              resize="none"
              class="chat-input"
            />
            <el-button
              type="primary"
              class="send-button"
              @click="sendMessage(currentGroup.groupId)"
            >
              发送
            </el-button>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<style scoped>
/* 全局容器：保持全屏高度与背景 */
.app-container {
  height: 100vh;
  background-color: #e6f7ef;
  overflow: hidden;
}

/* 主容器：左右布局高度适配 */
.main-container {
  height: calc(100vh - 20px);
  overflow: hidden;
  display: flex;
}

/* ———— 左侧小组列表样式（保留基础，优化细节） ———— */
.partner-aside {
  background-color: #fff;
  border-right: 1px solid #ebeef5;
  height: 100%;
  display: flex;
  flex-direction: column;
  width: 320px !important; /* 确保侧边栏宽度固定 */
}

.menu-header {
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fff;
  z-index: 1;
  display: flex;
  justify-content: space-between;
}

/* 弹窗标题居中 + 加粗 */
.el-dialog__title {
  text-align: center;
  font-weight: 600;
}

/* 表单项间距调整 */
.el-form-item {
  margin-bottom: 16px;
}

.menu-title {
  font-size: 16px;
  color: #303133;
  font-weight: 600;
  margin: 0;
}
/* 弹窗容器 */
.partner-dialog-container {
  padding: 10px 0;
}

/* 加载/空状态样式 */
.dialog-loading, .dialog-empty {
  text-align: center;
  padding: 30px 0;
  color: #909399;
}

/* 伙伴列表容器 */
.partner-list {
  max-height: 300px;
  overflow-y: auto;
  padding-right: 8px;
}

/* 单条伙伴项：名字左对齐，按钮右对齐 */
.partner-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 8px;
  background-color: #fff;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  transition: background-color 0.2s;
}

.partner-item:hover {
  background-color: #f5f7fa; /* hover时轻微变色 */
}

/* 名字样式 */
.partner-name {
  font-size: 15px;
  color: #303133;
}

/* 按钮与名字的间距 */
.partner-item .el-button {
  margin-left: 10px;
}

/* 滚动条优化 */
.partner-list::-webkit-scrollbar {
  width: 5px;
}

.partner-list::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background-color: #ddd;
}
/* 小组菜单容器：支持滚动，优化滚动体验 */
.partner-menu {
  border-right: none;
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

/* 小组菜单项：调整高度，适配小组信息展示 */
.partner-menu-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  height: 80px !important; /* 降低高度，避免列表拥挤 */
  margin: 0 8px 8px;
  border-radius: 8px;
  transition: all 0.3s;
  cursor: pointer;
  border: none; /* 清除默认边框 */
}

.partner-menu-item:hover {
  background-color: #f0f9f4;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 小组信息区域：优化文字排版 */
.partner-info {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 0;
  justify-content: center;
  height: 100%;
}

.partner-name {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  margin-bottom: 4px;
  line-height: 1.3;
}

.partner-desc {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  margin: 0;
  line-height: 1.2;
}

/* 无小组提示：优化样式 */
.empty {
  padding: 40px 0;
  text-align: center;
  color: #999;
  font-size: 14px;
}

/* ———— 右侧动态展示区样式（核心修改） ———— */
.content-main {
  padding: 0 20px 20px;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  flex: 1;
}

/* 小组头部样式：固定顶部，优化布局 */
.chat-header {
  margin-bottom: 16px;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  padding: 12px 20px;
}

.chat-header-content {
  display: flex;
  align-items: center;
}

/* 小组头部图标：方角设计，区别用户头像 */
.chat-header-avatar {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 16px;
  border: 1px solid #f0f0f0;
}

.chat-header-info {
  display: flex;
  flex-direction: column;
}

.chat-header-name {
  font-size: 17px;
  font-weight: 600;
  color: #333;
  margin-bottom: 3px;
  line-height: 1.2;
}

.chat-header-desc {
  font-size: 13px;
  color: #909399;
  line-height: 1.2;
}

.chat-header-btn{
  margin-left: 20px;
  width: 100px;
  height: 40px;
  font-size: large;
}
/* 动态列表卡片：占满中间区域，优化滚动 */
.chat-records-card {
  flex: 1;
  margin-bottom: 16px;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  overflow-y: auto;
  padding: 16px;
  height: auto !important; /* 清除原固定高度限制 */
}

/* 动态容器：限制最大宽度，避免大屏显示过宽 */
.chat-records-container {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

/* ———— 小组动态专属样式（核心新增） ———— */
/* 时间线基础样式优化 */
.el-timeline {
  padding-left: 16px;
  margin-top: 8px;
}

.el-timeline-item {
  margin-bottom: 24px;
  position: relative;
}

/* 时间戳样式：调整位置和颜色 */
.el-timeline-item__timestamp {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px !important;
  margin-left: 24px !important; /* 与发布者信息对齐 */
}

/* 发布者信息：头像+昵称+身份标识 */
.publisher-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  margin-left: 24px; /* 与时间线对齐 */
}

.publisher-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 10px;
  border: 1px solid #f0f0f0;
}

.publisher-nickname {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

/* “我”的身份标识：蓝色小标签 */
.is-me-tag {
  font-size: 12px;
  color: #165dff;
  background-color: rgba(22, 93, 255, 0.1);
  padding: 1px 6px;
  border-radius: 4px;
  margin-left: 6px;
}

/* 动态内容：优化背景和排版 */
.dynamic-content {
  color: #666;
  background-color: #f9f9f9;
}
.dynamic-content-mine {
  color: #fff;
   background-color: #40a9ff;
  line-height: 1.6;
}
.dynamic-content,
.dynamic-content-mine{
  font-size: 15px;
  line-height: 1.6;
  display: inline-block;
  max-width: 100%;
  word-wrap: break-word;
  padding: 12px 16px;
  border-radius: 8px;
  max-width: 70%;
  margin-left: 24px; /* 与发布者信息对齐 */
  word-break: break-all; /* 支持长文本换行 */
}
/* 无动态提示：优化居中样式 */
.no-dynamics {
  text-align: center;
  padding: 80px 0;
  color: #999;
  font-size: 14px;
}

/* ———— 输入区域样式（保留，优化布局） ———— */
.chat-input-card {
  margin-top: auto;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  padding: 16px;
}

.chat-input-container {
  display: flex;
  flex-direction: row !important; /* 横向排列：输入框+按钮 */
  gap: 12px;
  align-items: flex-end;
}

.chat-input {
  flex: 1;
  border-radius: 8px !important;
  resize: none;
  min-height: 80px;
  margin-bottom: 0 !important; /* 清除底部margin */
}

.send-button {
  height: 40px;
  width: 100px;
  border-radius: 8px !important;
  align-self: flex-end;
}

/* ———— 滚动条优化（提升体验） ———— */
.partner-menu::-webkit-scrollbar,
.chat-records-card::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.partner-menu::-webkit-scrollbar-thumb,
.chat-records-card::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background-color: #ccc;
}

.partner-menu::-webkit-scrollbar-track,
.chat-records-card::-webkit-scrollbar-track {
  background-color: #f9f9f9;
}

/* ———— 删除冗余聊天记录样式（不再需要） ———— */
.partner-avatar,
.chat-record-item,
.chat-record-me,
.chat-record-other,
.chat-record-content,
.timeline-item-me,
.timeline-item-other {
  display: none !important;
}
</style>
